/**
 * FileName: WechatIndexController
 * Author:   Leopold
 * Date:     2018/9/4 11:16
 * Description: 微信入口
 * History:
 */
package cn.mcsys.viewer.core.web;

import cn.mcsys.myadmin.dubbo.service.BackService;
import cn.mcsys.myadmin.modules.viewer.entity.AirViewerUser;
import cn.mcsys.viewer.core.utils.HttpRequestLocal;
import cn.mcsys.viewer.core.utils.WechatUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class IndexController {

    private static Logger logger = LoggerFactory.getLogger(IndexController.class);

    private static Map<String,Object> tokenMap = new HashMap<>();

    private static ThreadLocal<Map<String,Object>> local = new ThreadLocal<Map<String,Object>>(){
        @Override
        protected Map<String, Object> initialValue() {
            return tokenMap;
        }
    };

    @Autowired
    private BackService backService;

    private static HttpRequestLocal httpRequestLocal = HttpRequestLocal.getHttpRequestLocal();



    @RequestMapping("wechatindex")
    public String wechatIndex(String code,HttpServletResponse response) throws IOException {

        //设置跳转页面
        System.out.println("获取微信用户的信息中");
        //通过code去获取网页token和拉取用户数据
        String userinfo = null;
        try {
            userinfo = WechatUtil.getWechatUserinfo(code,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(userinfo);
        System.out.println("userinfo------------\n"+userinfo);
        if(userinfo == null || "".equals(userinfo)){
            response.sendRedirect("http://2018airshow.zhits.com.cn:10080");
        }
        JSONObject jsonObject = JSON.parseObject(userinfo);
        String openid = jsonObject.getString("openid");
        String nickname = jsonObject.getString("nickname");
        if(openid == null || nickname == null || "".equals(openid) || "".equals(nickname)){
            response.sendRedirect("http://2018airshow.zhits.com.cn:10080");
        }
        System.out.println(openid);
        System.out.println(nickname);
        AirViewerUser airViewerUser = new AirViewerUser();
        airViewerUser.setOpenid(openid);
        airViewerUser.setNickname(nickname);
//        1.判断是否在数据中
        AirViewerUser user = backService.selectByOpenidAndState(openid);

        setUserSession(user, airViewerUser,null);

        return "index";
    }

    @RequestMapping("appIndex")
    public String index(String nickName,String username,HttpServletResponse response) throws IOException {
        if(nickName == null || username == null){
            response.sendRedirect("http://2018airshow.zhits.com.cn:10080");
        }
        System.out.println("appIdex.nickName:"+nickName+",appIdex.username:"+username);
        AirViewerUser viewerUser1 = new AirViewerUser();
        viewerUser1.setNickname(nickName);
        viewerUser1.setUsername(username);
        AirViewerUser viewerUser = backService.selectByUsername(username);
        System.out.println("App接入");
        String token = setUserSession(viewerUser, viewerUser1, null);
        System.out.println("进入APP接口结束");
        response.setHeader("Authorization",token);
        return "index";
    }

    private String setUserSession(AirViewerUser oldUser,AirViewerUser currentUser,String state){
        String token = null;
        if(oldUser == null){
//            设置公众号来源
            currentUser.setUserSource(state);
            backService.save(currentUser);
            logger.debug("设置新用户的session");
            AirViewerUser airViewerUser = backService.selectByUsername(currentUser.getUsername());
            if(airViewerUser == null){
                airViewerUser = backService.selectByOpenidAndState(currentUser.getOpenid());
            }
            HttpRequestLocal.setUserSession(airViewerUser);

            System.out.println("获取新用户session信息："+airViewerUser);
        }else {
            logger.debug("设置老用户的session");
            HttpRequestLocal.setUserSession(oldUser);
        }
        return token;
    }

}
